package com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql;

import com.xymtop.sqlcater.core.sql.sqlparser.tosql.utils.AppContentUtil;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.xmind.parse.ParseXmind;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.xmind.SaveType;
import org.xmind.core.CoreException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//需要查询的sql入口
public class SqlApp {

    //解析时需要用到的
    private List<AppContent> appContents = new ArrayList<>();
    //运行
    public SqlApp  run(String path) throws IOException, CoreException {

        File file = new File(path);


        //如果是
        if(file.isDirectory()){
            File[] files = file.listFiles();

            for(File fileTemp : files){
                if(fileTemp.isFile()){
                    AppContent appContent = getAppContent(fileTemp);
                    this.appContents.add(appContent);


                    AppContentUtil.appContentMap.put(appContent.getName(),appContent);
                }
            }
        }else {
            AppContent appContent = getAppContent(file);
            AppContentUtil.appContentMap.put(appContent.getName(),appContent);
            this.appContents.add(appContent);
        }


        return this;
    }


    public  AppContent getAppContent(File fileTemp) throws IOException, CoreException {
        AppContent appContent = new AppContent();
        //判断文件后缀
        String fileName = fileTemp.getName();
        String[] split = fileName.split(".");
        String jsons = fileName.substring(fileName.length() - 4, fileName.length());
        String xminds = fileName.substring(fileName.length() - 5, fileName.length());

        //解析好的文件名称
        if(fileName!=null){
            appContent.setName(fileName);
        }

        if(jsons.equals("json")){

            //如果是json创建上下文

            appContent.setPath(fileTemp.getAbsolutePath());
            appContent.Start().buildSql();


        }

        if(xminds.equals("xmind")){
            //解析xmind
            appContent = ParseXmind.add(fileTemp.getAbsolutePath()).parse();
            appContent.buildSql();
        }


        return appContent;
    }

    //输出写入
    public void out(Boolean isCheck, SaveType[] saveTypes) throws IOException, CoreException, NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        if(!this.appContents.isEmpty()){


            for(AppContent app : appContents){

                app.out(isCheck,saveTypes);
            }
        }
    }
}
